package com.zztl.infiniteBand.ui.activity

import android.app.Activity
import android.bluetooth.BluetoothGatt
import android.os.Build
import android.os.Handler
import android.view.View
import android.view.animation.AnimationUtils
import android.view.animation.LinearInterpolator
import butterknife.OnClick
import com.clj.fastble.BleManager
import com.clj.fastble.callback.BleConnectCallback
import com.clj.fastble.callback.BleScanCallback
import com.clj.fastble.data.BleDevice
import com.clj.fastble.exception.BleException
import com.clj.fastble.scan.BleScanRuleConfig

import com.zztl.infiniteBand.BraceletApplication
import com.zztl.infiniteBand.R
import com.zztl.infiniteBand.base.BaseMvpActivity
import com.zztl.infiniteBand.dao.BindedWatchBean
import com.zztl.infiniteBand.eventbus.ConnectedEvent
import com.zztl.infiniteBand.greendao.BindedWatchBeanDao
import com.zztl.infiniteBand.model.BindedDeviceBean
import com.zztl.infiniteBand.model.BluetoothDeviceBean
import com.zztl.infiniteBand.net.requestBean.BindDeviceRequest
import com.zztl.infiniteBand.presenter.BindDevicePresenter
import com.zztl.infiniteBand.ui.view.dialog.DeviceDialog
import com.zztl.infiniteBand.ui.view.mvpview.UploadImageView
import com.zztl.infiniteBand.util.PermissionUtils
import com.zztl.infiniteBand.util.device.DeviceUtil
import com.zztl.infiniteBand.util.toast
import kotlinx.android.synthetic.main.activity_link.*
import org.greenrobot.eventbus.EventBus
import java.lang.ref.WeakReference

class LinkActivity : BaseMvpActivity<UploadImageView, BindDevicePresenter>(), UploadImageView {


    /*  @BindView(R.id.tv1)
      lateinit var tv1: TextView
      @BindView(R.id.btn_search)
      lateinit var btn_search: ImageView*/


    private var selectedPosition = -1
    private var isBind=false

    private var isConnecting: Boolean = false
    private var mDeviceDialog: DeviceDialog? = null
    private val mHandler: Handler = Handler()
    //    private var linkDevice: BleDevice? = null
    var bindedMacList = mutableListOf<String>()  //已绑定的设备mac值列表

    lateinit var mBindDevicePresenter: BindDevicePresenter
    val deviceList by lazy {
        ArrayList<BluetoothDeviceBean>()
    }
    val macList by lazy {
        ArrayList<String>()
    }
//    lateinit var mCountDownTimer: CountDownTimer



    private val mPermissionGrant = object : PermissionUtils.PermissionGrant {
        override fun onPermissionGranted(requestCode: Int) {
            when (requestCode) {
                PermissionUtils.CODE_ACCESS_COARSE_LOCATION -> {
                    try {
                        btn_search.isEnabled = false
                        tv1.text = getString(R.string.正在搜索设备)
                        startAnim(btn_search)
                        deviceList.clear()
                        macList.clear()
//                        mCountDownTimer.start()
                        startScan()
                    } catch (e: Exception) {
                    }
                }
            }
        }
    }


    override fun setLayoutId(): Int = R.layout.activity_link


    override fun initBase() {
     /*   mCountDownTimer = object : CountDownTimer(1000 * 15, 1000) {
            override fun onTick(millisUntilFinished: Long) {
            }

            override fun onFinish() {
                startScan()
                btn_search.isEnabled = true
                stopAnim(btn_search)
                tv1.text = getString(R.string.点击下方按钮搜索设备)
                handleScanResult()
            }
        }*/

        BraceletApplication.getmDaoSession()?.bindedWatchBeanDao?.loadAll()?.apply {
            forEach {
                bindedMacList.add(it.imei)
            }
        }
        BleScanRuleConfig.Builder().setAutoConnect(false).setDeviceName(true, BleManager.WATCH_NAME).setScanTimeOut(15*1000).build().apply {
            BleManager.getInstance().initScanRule(this)
        }
    }


    @OnClick(R.id.btn_search, R.id.btn_nolink)
    fun click(view: View) {
        when (view.id) {
            R.id.btn_nolink -> finish()
            R.id.btn_search -> {
                if (!DeviceUtil.bluetoothIsEnabel()) {
                    DeviceUtil.openBluetooth()
                    return
                }
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (!DeviceUtil.isGpsEnable(this)) {
                        DeviceUtil.showturnOnGPSAlertView(this)
                        return
                    }
                }
                PermissionUtils.requestPermission(this, PermissionUtils.CODE_ACCESS_COARSE_LOCATION, mPermissionGrant)

            }
        }
    }


    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>,
                                            grantResults: IntArray) {
        PermissionUtils.requestPermissionsResult(this, requestCode, permissions, grantResults, mPermissionGrant)
    }


    private fun startAnim(view: View) {
        view.animation = AnimationUtils.loadAnimation(this, R.anim.rotate_animation)?.apply {
            this.interpolator = LinearInterpolator()
            start()
        }

    }


    private fun stopAnim(view: View?) {
        view?.clearAnimation()
    }

    private fun startScan() {
        BleManager.getInstance().scan(object : BleScanCallback() {
            override fun onScanStarted(success: Boolean) {
//                bleDeviceList.clear()
//                linkDevice = null
                deviceList.clear()
                macList.clear()
                tv1.text =getString(R.string.正在搜索可用设备)
                btn_search.isEnabled = false
                startAnim(btn_search)
            }

            override fun onScanning(bleDevice: BleDevice) {
                if (!macList.contains(bleDevice.mac) && !bindedMacList.contains(bleDevice.mac)) {
                    deviceList.add(BluetoothDeviceBean(bleDevice, false, false))
                    macList.add(bleDevice.mac)
                }

            }

            override fun onScanFinished(scanResultList: List<BleDevice>) {
                btn_search.isEnabled = true
                stopAnim(btn_search)
                tv1.text = getString(R.string.点击下方按钮搜索设备)
                handleScanResult()
            }
        })
    }


    private fun handleScanResult() = if (deviceList.size == 0) {
        toast(getString(R.string.未搜索到可用设备))
    } else {
        mDeviceDialog = DeviceDialog.Builder(this).setMessage(getString(R.string.选择设备))
                .setListData(deviceList)
                .setClickListener(object : DeviceDialog.Builder.ClickListener {
                    override fun cancel() {

                    }

                    override fun comfirm() {

                    }
                })
                .setItemClickListener(object : DeviceDialog.Builder.ItemClickListener {
                    override fun itemClick(position: Int) {
                        connect(deviceList[position].device)
                        selectedPosition = position
                    }
                }).create().apply {
                    showDialog()
                }
    }


    override fun createPresenter(): BindDevicePresenter {
        mBindDevicePresenter = BindDevicePresenter()
        return mBindDevicePresenter
    }


    private fun connect(bleDevice: BleDevice) {
        isBind=false
        BleManager.getInstance().connect(bleDevice, MyBleConnectCallback(this))
    }



    private inner class MyBleConnectCallback: BleConnectCallback {
        private var weakReference:WeakReference<Activity>

        constructor(activity: Activity){
            weakReference= WeakReference(activity)
        }

        override fun onStartConnect() {
        }

        override fun onConnectFail(bleDevice: BleDevice, exception: BleException) {
            mDeviceDialog?.resetUi()
            if(!isBind) {
                weakReference.get()?.toast(getString(R.string.连接失败))
            }
        }

        override fun onConnectSuccess(bleDevice: BleDevice, gatt: BluetoothGatt, status: Int) {
//            linkDevice = bleDevice
            if (selectedPosition != -1) {
                mDeviceDialog?.setConnectedUi(selectedPosition)
            }
             val queryBuilder = BraceletApplication.getmDaoSession()?.bindedWatchBeanDao?.queryBuilder()
             val list = queryBuilder?.where(BindedWatchBeanDao.Properties.Mac.eq(bleDevice.mac))?.list()
             if (list?.size == 0) {
                 bindWatch(bleDevice)
             }else{
//                 skipActivity(this@LinkActivity,MainActivity::class.java)
                 BleManager.getInstance().disconnectAllDevice()
                 weakReference.get()?.toast(getString(R.string.无法绑定更多设备))
                 finish()
             }


        }

        override fun onDisConnected(isActiveDisConnected: Boolean, bleDevice: BleDevice, gatt: BluetoothGatt, status: Int) {
            mDeviceDialog?.resetUi()
//            weakReference.get()?.toast(getString(R.string.断开连接了))
//            EventBus.getDefault().post(ConnectedEvent(false))
        }
    }


    private fun bindWatch(bleDevice: BleDevice) {
        isBind=true
        bleDevice.let {
            it.device?.let { device ->
                mBindDevicePresenter.bindDevice(BindDeviceRequest(device.address, device.address, DeviceUtil.DEVICE_NAME, device.address, 1), this)
            }
        }
    }


    override fun loadSuccess() {
        mBindDevicePresenter.getBindDevice(this)
    }

    override fun loadFail(msg: String?) {
        toast(msg!!)
        BleManager.getInstance().disconnectAllDevice()
        EventBus.getDefault().post(ConnectedEvent(false))
//        finish()
    }

    override fun getBindDeviceList(bean: BindedDeviceBean) {

        BraceletApplication.getmDaoSession()?.bindedWatchBeanDao?.let {

//            it.deleteAll()
            it.insertOrReplaceInTx(bean.data?.rows?.filter { rowsBean -> rowsBean.mac!!.isNotEmpty() }?.flatMap { rowBean ->
                listOf(
                        BindedWatchBean().apply {
                            bluetoothId = rowBean.bluetoothId
                            imei = rowBean.imei
                            mac = rowBean.mac
                            name = rowBean.name
                            type = rowBean.type
                        }
                )
            })
        }
        EventBus.getDefault().post(ConnectedEvent(true))

        skipActivity(this, MainActivity::class.java)
    }

    override fun getBindDeviceFail() {
        EventBus.getDefault().post(ConnectedEvent(false))
        BleManager.getInstance().disconnectAllDevice()
//        finish()
    }


    override fun onDestroy() {
        stopAnim(btn_search)
        super.onDestroy()
    }


}
